﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using log4net;
using log4net.Appender;

namespace WHO_Auth_TNG_Win {
    internal static class Program {
        private static readonly ILog log = LogManager.GetLogger("WHO-Auth TNG");

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        private static void Main() {
            initLogging();
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(
                    CurrentDomain_UnhandledException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainWindow());
        }

        private static void initLogging() {
            var ca = new log4net.Appender.ConsoleAppender();
            var layout = new log4net.Layout.PatternLayout("%d{dd MMM yyyy HH:mm:ss,fff} %-5p [%-25C{1}  - %-35M]: %m%n");
            //var fa = new log4net.Appender.RollingFileAppender {File = "logfile.log", MaxFileSize = 5*1024*1024, AppendToFile = true, MaxSizeRollBackups = -1, RollingStyle = RollingFileAppender.RollingMode.Size, StaticLogFileName = true, Layout = new log4net.Layout.PatternLayout("%d{dd MMM yyyy HH:mm:ss,fff} %-5p [%-25C{1}  - %-35M]: %m%n"), Threshold = log4net.Core.Level.Info, LockingModel = new RollingFileAppender.MinimalLock()};
            var fa = new FileAppender(new log4net.Layout.PatternLayout("%d{dd MMM yyyy HH:mm:ss,fff} %-5p [%-25C{1}  - %-35M]: %m%n"), "log.log",false);
            //fa.Layout = new log4net.Layout.PatternLayout("%d{HH:mm:ss} %-5p [%-25C{1}  - %-35M]: %m%n");
            fa.Threshold = log4net.Core.Level.Info;
            ca.Layout = new log4net.Layout.PatternLayout("%d{HH:mm:ss,fff} %-5p [%-15C{1}  - %-30M]: %m%n");
            log4net.Config.BasicConfigurator.Configure(ca);
            log4net.Config.BasicConfigurator.Configure(fa);
        }

        private static void CurrentDomain_UnhandledException
            (object sender, UnhandledExceptionEventArgs e) {
            try {
                Exception ex = (Exception) e.ExceptionObject;
                log.Fatal(ex.Message, ex);

                MessageBox.Show("An unexpected error occured. Sorry for the inconvenience. If possible, please send the log file to the author."
                                , "Fatal Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Stop);
            } finally {
                Application.Exit();
            }
        }
    }
}